package com.agileai.portal.extend.mobile;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;

import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataParam;
import com.agileai.hotweb.common.HttpClientHelper;
import com.agileai.hotweb.common.StringTemplateLoader;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

public class RequestProxyHandler extends BaseHandler{
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ViewRenderer prepareDisplay(DataParam param){
		String responseText = FAIL;
		String requestJsonText = this.getInputString();// format is {"realURL":"YourURL"}
		try {
			JSONObject jsonObject = new JSONObject(requestJsonText);
			String realURLExpressionTemp = jsonObject.getString("realURL");
			String realURLExpression = realURLExpressionTemp.replace("#currentUserId#", "${currentUserId}");
			User user = (User)this.getUser();
			HashMap varMap = new HashMap();
			varMap.put("currentUserId", user.getUserCode());
			String realURL = this.buildMergedURL(varMap, realURLExpression);
			
			HttpClientHelper httpClientHelper = new HttpClientHelper();
			responseText = httpClientHelper.retrieveGetReponseText(realURL);
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@SuppressWarnings("rawtypes")
	private String buildMergedURL(HashMap varMap,String urlExpression){
		String result = urlExpression;
		try {
			StringWriter writer = new StringWriter();
			String encoding = "UTF-8";
	    	Configuration cfg = new Configuration();
	    	cfg.setTemplateLoader(new StringTemplateLoader(urlExpression));  
	    	cfg.setEncoding(Locale.getDefault(),encoding);
	        cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
	    	Template temp = cfg.getTemplate("");
	    	temp.setEncoding(encoding);
	        temp.process(varMap, writer);
	        writer.flush();
	        result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
